/** @jsxImportSource @emotion/react */
import { jsx } from "@emotion/react";
import * as React from "react";
// import {Button, ButtonProps, ButtonRefComp, ButtonSize, getHeight} from "./Button";
import PropTypes from "prop-types";
// import { IconWrapper } from "./IconWrapper";
// import { IconX } from "./Icons";
// import { useTheme } from "./Theme/Providers";
// import {OnPressFunction} from "./Hooks/touchable-hook";

import {
    ButtonProps, IconWrapper, ButtonSize, getHeight, ButtonRefComp,
    IconX,
    useToast,
    InputPure,
    SuffixInput,
    Dialog,
    Text,
    Button,
    useTheme,
    InputLine,
    Input,
    IconCloud,
    List,
    ListItem,
    Avatar,
    ResponsivePopover,
    IconPackage,
    IconMoreVertical,
    Select,
    CommitInput,
    CheckSwitch, InputDatalist, Layer, IconChevronUp, IconChevronDown, Collapse, useCollapse, VisuallyHidden
} from "customize-easy-ui-component";


import {
    Children,
    cloneElement,
    forwardRef,
    isValidElement,
    useEffect,
    useLayoutEffect,
    useMemo,
    useRef,
    useState
} from "react";
import { mergeRefs } from "react-merge-refs";
import {
    autoUpdate,
    flip,
    FloatingPortal,
    offset,
    shift,
    useRole,
    useDismiss,
    useFloating,
    FloatingFocusManager,
    useInteractions,
    useListNavigation,
    useTypeahead,
    FloatingOverlay
} from "@floating-ui/react";



export const CMenuItem = forwardRef<
    HTMLButtonElement,
    { label: string; disabled?: boolean }
    >(({ label, disabled, ...props }, ref) => {
    return (
        <button {...props} ref={ref} role="menuitem" disabled={disabled}>
            {label}
        </button>
    );
});

interface Props {
    label?: string;
    nested?: boolean;
}

//鼠标右键点击：
export const ContextMenu = forwardRef<any, Props & React.HTMLProps<HTMLButtonElement>>(
    ({ children }, ref) => {
        const [activeIndex, setActiveIndex] = useState<number | null>(null);
        const [open, setOpen] = useState(false);

        const listItemsRef = useRef<Array<HTMLButtonElement | null>>([]);
        const listContentRef = useRef(
            Children.map(children, (child) =>
                isValidElement(child) ? child.props.label : null
            ) as Array<string | null>
        );

        const { x, y, reference, floating, strategy, refs, context } = useFloating({
            open,
            onOpenChange: setOpen,
            middleware: [offset({ mainAxis: 5, alignmentAxis: 4 }), flip(), shift()],
            placement: "right-start",
            strategy: "fixed",
            whileElementsMounted: autoUpdate
        });

        const { getFloatingProps, getItemProps } = useInteractions([
            useRole(context, { role: "menu" }),
            useDismiss(context),
            useListNavigation(context, {
                listRef: listItemsRef,
                activeIndex,
                onNavigate: setActiveIndex,
                focusItemOnOpen: false
            }),
            useTypeahead(context, {
                enabled: open,
                listRef: listContentRef,
                onMatch: setActiveIndex,
                activeIndex
            })
        ]);

        const mergedReferenceRef = useMemo(() => mergeRefs([ref, reference]), [
            reference,
            ref
        ]);

        //直接跟随鼠标点击的[x,y]位置，也是ref绑定处理==传递[x,y]模式。 【奇怪】getBoundingClientRect覆盖掉原生函数？ ref, reference的都有覆盖这个接口函数。

        useEffect(() => {
            function onContextMenu(e: MouseEvent) {
                e.preventDefault();
                mergedReferenceRef({
                    getBoundingClientRect() {
                        return {
                            x: e.clientX,
                            y: e.clientY,
                            width: 0,
                            height: 0,
                            top: e.clientY,
                            right: e.clientX,
                            bottom: e.clientY,
                            left: e.clientX
                        };
                    }
                });
                setOpen(true);
            }

            document.addEventListener("contextmenu", onContextMenu);
            return () => {
                document.removeEventListener("contextmenu", onContextMenu);
            };
        }, [mergedReferenceRef]);

        useLayoutEffect(() => {
            if (open) {
                refs.floating.current?.focus();
            }
        }, [open, refs.floating]);

        return (
            <FloatingPortal>
                {open && (
                    <FloatingOverlay lockScroll>
                        <FloatingFocusManager context={context} initialFocus={-1}>
                            <div
                                {...getFloatingProps({
                                    className: "ContextMenu",
                                    ref: floating,
                                    style: {
                                        position: strategy,
                                        top: y ?? 0,
                                        left: x ?? 0
                                    }
                                })}
                            >
                                {Children.map(
                                    children,
                                    (child, index) =>
                                        isValidElement(child) &&
                                        cloneElement(
                                            child,
                                            getItemProps({
                                                tabIndex: activeIndex === index ? 0 : -1,
                                                role: "menuitem",
                                                className: "MenuItem",
                                                ref(node: HTMLButtonElement) {
                                                    listItemsRef.current[index] = node;
                                                }
                                            })
                                        )
                                )}
                            </div>
                        </FloatingFocusManager>
                    </FloatingOverlay>
                )}
            </FloatingPortal>
        );
    }
);

